package com.bite.gateway.filter;


import com.bite.common.pojo.Result;
import com.bite.common.utils.JWTUtils;
import com.bite.gateway.prosperity.AuthWhiteName;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements Ordered, GlobalFilter {

    @Autowired
    private ObjectMapper objectMapper;

    // 通过 nacos 配置来获取 这样可以减少部署次数
//    private final List<String> whitePath = List.of("/user/login", "/user/register");

    @Autowired
    private AuthWhiteName authWhiteName;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (match(path, authWhiteName.getUrl())) {
            // 放行
            return chain.filter(exchange);
        }

        String userToken = request.getHeaders().getFirst("user_token");
        if (!StringUtils.hasLength(userToken)) {
            // 没有token
            return unAuthorizeToken(exchange, "token不存在，请先登录");
        }

        log.info("从header中获取token:{}",userToken);
        //验证用户token
        Claims claims = JWTUtils.parseJWT(userToken);
        if (claims == null){
            return unAuthorizeToken(exchange, "token已过期或者不合法");
        }

        return chain.filter(exchange);
    }

    private boolean match(String path, List<String> authWhiteName) {
        if (authWhiteName == null || authWhiteName.isEmpty())  {
            return false;
        }
        return authWhiteName.contains(path);
    }

    @SneakyThrows
    private Mono<Void> unAuthorizeToken(ServerWebExchange exchange, String errMsg) {
        log.error("[用户验证失败] url: {}", exchange.getRequest().getURI().getPath());

        // 设置返回类型格式
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        Result result = Result.fail(errMsg);

        DataBuffer dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));

    }

    @Override
    public int getOrder() {
        return -200;
    }
}
